package it.unibo.imola.gui;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.PlatformUI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SaveCommandHandler extends AbstractHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		FileDialog fileDialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
		fileDialog.setFilterExtensions(new String[] { "*.imola", "*.txt" });
		
		String fileName = fileDialog.open();

		if (fileName == null || fileName.isEmpty())
			return null;

		String[] filterExtensions = fileDialog.getFilterExtensions();
		int choosenFilterIndex = 1;

		if (fileDialog.getFilterIndex() >= 0) {
			choosenFilterIndex = fileDialog.getFilterIndex();
		}

		String choosenFilterExtension = filterExtensions[choosenFilterIndex].substring(1);  // da
																							// "*.xxx"
																							// restituisce
																							// ".xxx"
		if (!fileName.endsWith(choosenFilterExtension)) {
			fileName += choosenFilterExtension;
		}

		if (logger.isDebugEnabled())
			logger.debug("fileName=" + fileName);

		File file = new File(fileName);

		EditorView editorView = (EditorView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(EditorView.ID);
		String text = editorView.getStyledText().getText();

		if (text == null) {
			if (logger.isDebugEnabled())
				logger.debug("text == null");
			text = "";
		}

		try {
			FileUtils.write(file, text);
		} catch (Exception e) {
			MessageDialog errorDialog = new MessageDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", null, e.getMessage(), MessageDialog.ERROR, new String[]{"OK"}, 0);
			errorDialog.open();
		}
		return null;
	}

}
